package org.onejava.db.mapping;


import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.onejava.db.DbcpConnection;
import org.onejava.db.transaction.TransactionEntity;


/**
 * 
 * 基础SQL处理类
 * 功能：
 * 1.解析SQL和结果集
 * 2.处理简单的事务(非嵌套)
 * @author frost
 *
 */
public class BaseSqlMapping {
	protected static final ThreadLocal<TransactionEntity> TRANSACTION_ENTITY = new ThreadLocal<TransactionEntity>();
	protected  static  Log log = LogFactory.getLog(BaseSqlMapping.class);  

	/**
	 * 开启事务
	 * @returny
	 * @throws Exception
	 */
	public boolean startTran()throws Exception{
		if(TRANSACTION_ENTITY.get()==null){
			TRANSACTION_ENTITY.set(new TransactionEntity(0, DbcpConnection.getConnection(), 0));
		}
		try {
			TRANSACTION_ENTITY.get().getConn().setAutoCommit(false);
			log.info("事务开启了");
		} catch (Exception e) {
			closeSou();
			throw new Exception(e);
		}finally{
		}
		return true;
	}
	
	
	/**
	 * 关闭链接
	 * @throws Exception
	 */
	public void closeSou() throws Exception{
		if(TRANSACTION_ENTITY.get()!= null&&!TRANSACTION_ENTITY.get().getConn().isClosed()){ 
			TRANSACTION_ENTITY.get().getConn().close();
			TRANSACTION_ENTITY.remove();
		}
		log.info("数据库资源关闭");
	}
	
	/**
	 * 事务的提交
	 * @throws Exception 
	 */
	public  void   runCommit() throws Exception{
		try {
			TRANSACTION_ENTITY.get().getConn().commit();
		} catch (SQLException e) {
			throw new Exception(e);
		}finally{
			log.info("事务提交了");
			closeSou();
		}
	}
	
	/**
	 * 事务的回滚
	 * @throws Exception 
	 */
	public  void  runRollBack() throws Exception{
		try {
			TRANSACTION_ENTITY.get().getConn().rollback();
		} catch (SQLException e) {
			throw new Exception(e);
		}finally{
			log.info("事务回滚了");
			closeSou();
		}
	}
	
	/**
	 * 解析SQL
	 * @param sql
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	protected  Map<String, Object> sqlAnalyze2(String sql,Map<String,String> map) throws Exception{
		List<String> list = new ArrayList<String>();
		while(true){
		   int start =sql.indexOf("#");
		   if(start==-1){
			   break;
		   }
		   int over =sql.indexOf("#",start+1);
		   if(over==-1){
			   throw new Exception("SQL中有多余的'#'");
		   }
		   String key = sql.substring(start+1, over);
		   list.add(key);
		   String value =map.get(key);
		   if(value==null){
			   throw new Exception("SQL中的属性"+key+"没有对应的值");
		   }
		   sql = sql.replaceAll("#"+key+"#", "?");
		}
		
		List<String> list2 = new ArrayList<String>();
		for(int i=0;i<list.size();i++){
			list2.add(map.get(list.get(i)));
		}
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("sql", sql);
		map2.put("list", list2);
		
		return map2;
	}
	/**
	 * 处理结果集
	 * @param rs
	 * @return
	 * @throws Exception
	 */
	protected List<Map<String, Object>> getList(ResultSet rs) throws Exception{
		ResultSetMetaData resultsetmetadata = rs.getMetaData();
		int size = resultsetmetadata.getColumnCount();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		while(rs.next()){
			Map<String, Object> map = new HashMap<String, Object>();
			for(int i=0;i<size;i++){
				Object value=rs.getObject(resultsetmetadata.getColumnLabel(i+1));
				map.put(resultsetmetadata.getColumnLabel(i+1), value);
			}
			list.add(map);
		}
			return list;
	}
}
